/**
 * Created by Lihn on 15-6-19.
 */
;
(function () {
	//数组去除重复
	var toRepeat = function(arr)
	{
		var n = []; //一个新的临时数组
		for(var i = 0; i < arr.length; i++) //遍历当前数组
		{
			//如果当前数组的第i已经保存进了临时数组，那么跳过，
			//否则把当前项push到临时数组里面
			if (n.indexOf(arr[i]) == -1) n.push(arr[i]);
		}
		return n;
	}
    //定义画布环境变量及场景
    var canvas = null; //创建一个画布
    var stage = null; //创建一个舞台对象
    var scene = null; //定义一个场景对象

    //定义绘制直线的线段
    var beginNode = null;
    var tempNodeA = null;//
    var tempNodeZ = null;
    var tempLink = null;
    var rightMenuOperObj = null;
	//告警处理setIntervalId
	var intervalId;
	//存放告警拓扑节点信息
	//var nodeAlarm={node:拓扑节点,alarmLevel:告警级别,alarmNumber:告警数量}
	var nodeAlarms=[];


    var operState = {
        state_default:"default",
        state_fullscreen:"fullscreen",
        state_center:"center",
        state_magnifier:"magnifier",
        state_shrink:"shrink",
        state_recover:"recover",
        state_line:"line",
        state_foldline:"foldline",
        state_eagleye:"eagleye"
    };

    var state = operState.state_default;

    var height, width;//定义容器的高度和宽度

    /**
	* 创建工具条
	*/
    var createToolBar = function(target){

        var css ;
        var background_image ;
        var background_size;
        var isSelected = false;
        
        var $toolbar = $("<div class='detail_r'/>");
        //var $tool = $("<div class='tool'/>");
        var $container = $("<div class='tool_bar'/>");
        //$tool.append($container);
        //$container.append($("<span value='default'/>").addClass("default").attr("title","默认"));
        //$container.append($("<span value='fullscreen'/>").addClass("fullscreen").attr("title","全屏"));
        $container.append($("<span  value='center'/>").addClass("center").attr("title","居中"));
        $container.append($("<span value='magnifier'/>").addClass("magnifier").attr("title","放大"));
         $container.append($("<span  value='shrink'/>").addClass("shrink").attr("title","缩小"));
        $container.append($("<span  value='recover'/>").addClass("recover").attr("title","恢复"));
        //$container.append($("<span value='line'/>").addClass("line").attr("title","连线"));
        //$container.append($("<span value='foldline'/>").addClass("foldline").attr("title","L形连线"));
        $container.append($("<span name=false  value='eagleye'/>").addClass("eagleye").attr("title","鹰眼"));

        //var $select = $("<select/>");
        //$container.append($select.append("<option value='circlelayout'>圆形布局</option>"));
        //$container.append($select.append("<option value='treelayout'>树形布局</option>"));
        $toolbar.append($container);
        if( target){
            target.append($toolbar);
        }
		//布局切换
        $(target).find("select").change(function (event) {
            var value = $(event.target).attr("value");
            var layout = null;
            switch (value) {
                case "circlelayout":
                	scene.circleLayout();
                    break;
                case "treelayout":
                	scene.treeLayout();
                    break;
            }
        });
        var css ;
        var background_image ;
        var background_size;
        var isSelected = false;

        $(".tool_bar span").mouseover(function(){
            background_image = $(this).css("background-image");
            background_size = $(this).css("background-size");
            css = $(this).attr("class");
            $(this).attr("class","over");
            $(this).css("background-image",background_image);
            $(this).css("background-size",background_size);
        }).mouseout(function(){
            $(this).removeClass('over');
            $(this).addClass(css);
            $(this).css("background-image",background_image);
            $(this).css("background-size",background_size);
        });
        
        var dd = self.location.href;
        if(dd.indexOf("=") == -1){
        	dd = "";
        }else{
        	dd = dd.substring(dd.indexOf("=")+1);
        }

        $(".tool_bar span").click(function(){
            $(this).siblings().removeClass('selected');
            $(this).addClass("selected");

            var action = $(this).attr("value");
            state = action;
            switch(action) {
                case operState.state_default://箭头
                    clearDrawLineState();//
                    break;
                case operState.state_fullscreen: // 全屏
                	runPrefixMethod(stage.canvas, "RequestFullScreen");
                    break;
                case operState.state_center: //居中
                    stage.centerAndZoom(); //缩放并居中显示
                    break;
                case operState.state_magnifier: // 放大
                    stage.zoomOut();
                    break;
                case operState.state_shrink: //缩小
                    stage.zoomIn();
                    break;
                case operState.state_recover: //恢复
                    stage.recover();
                    break;
                case operState.state_line: //直线
                    beginDrawLine(action);
                    break;
                case operState.state_foldline: //折线
                    beginDrawLine(action);
                    break;
                case operState.state_eagleye: //鹰眼
                    var flag = $(this).attr("name");
                    if(flag == 'false'){
                        stage.eagleEye.visible = true;
                        $(this).attr("name", 'true');
                    }else{
                        stage.eagleEye.visible = false;
                        $(this).attr("name", 'false');
                    }
                    break;
            }
        });
        return $toolbar;
    }
	var clearDrawLineState = function(){
        return;

    }
	//全屏
	var runPrefixMethod = function(element, method) {
        var usablePrefixMethod;
        ["webkit", "moz", "ms", "o", ""].forEach(function(prefix) {
                if (usablePrefixMethod) return;
                if (prefix === "") {
                    // 无前缀，方法首字母小写
                    method = method.slice(0,1).toLowerCase() + method.slice(1);
                }
                var typePrefixMethod = typeof element[prefix + method];
                if (typePrefixMethod + "" !== "undefined") {
                    if (typePrefixMethod === "function") {
                        usablePrefixMethod = element[prefix + method]();
                    } else {
                        usablePrefixMethod = element[prefix + method];
                    }
                }
            }
        );

        return usablePrefixMethod;
    };
    //创建拓扑组件
    var createJtopo = function(target,width,height){
        var $canvas = $("<canvas width='"+width+"px' height='"+height+"px' ondrop='dragDrop(event)'></canvas>");
        target.append($canvas);
        $canvas[0].ondrop = function(ev){
            console.info("drop");
            var dt = ev.dataTransfer;
            var id = dt.getData("id");
            console.info("drop node :"+id);
            addNode(id,ev,true);
            ev.preventDefault();
        }

        $canvas[0].ondragover = function(ev){
            ev.preventDefault();
            return true;
        }
        return target;
    }
    
    var initTopo = function (topoData) {
        if (topoData) {
            //加载容器
            if (topoData.containers) {
                topoData.containers.forEach(function (contain) {
                    if (contain) {
                        // 不指定布局的时候，容器的布局为自动(容器边界随元素变化）
                        var container = new JTopo.Container(contain.name); //创建一个容器
						
						container.fillColor ='241,241,241';
						container.alpha = 0.9;
                        container.fontColor = '0,0,0';
                        container.font = '10pt 微软雅黑';
                        container.borderRadius = 20; // 圆角
                        container.x = contain.x;
                        container.y = contain.y;
                        container.id = contain.id;
						container.icon= contain.icon;
                        scene.add(container);
                    }
                });
            }

            //加载节点
            if (topoData.nodes) {
                topoData.nodes.forEach(function (n) {
					var node = new JTopo.Node();
					node.id = n.id;
					node.setImage(n.icon, true);
					node.text = n.name; //标题
					node.icon = n.icon;
					node.bundBz=n.bundBz;
					node.x = n.x;
					node.y = n.y;

					node.font = '10px'; // 部件字体
					//设置部件图片属性
					node.fontColor = "0,0,0"
					node.borderRadius = 5; // 圆角
					node.borderWidth = 2; // 边框的宽度
					node.borderColor = '255,255,255'; //边框颜色
					node.alpha = 1; //透明度
					scene.add(node);
					
					//为部件分配组
					initContainerJTop(scene, node);
                    
                });
            }

            if (topoData.links) {
                topoData.links.forEach(function (l) {
                    //循环节点，查找与线对应的节点然后创建连线
                    var nodeA = null;
                    var nodeZ = null;
                    var link = null;

                    scene.childs.forEach(function (element) {
                        if (element instanceof JTopo.Node) {
                            if (l.fromid == element.id) {
                                nodeA = element;
                            }
							if (l.toid == element.id) {
                                nodeZ = element;
                            }
                        }
                    })
                    if (nodeA != null && nodeZ != null) {
                        if (l.isFoldLine) {
                            link = new JTopo.FoldLink(nodeA, nodeZ, l.text);
                        } else {
                            link = new JTopo.Link(nodeA, nodeZ, l.text);
                        }
                        if(l.hasArrow){
                        	link.arrowsRadius = 15; //箭头大小
                        }
                        link.font = '14px 微软雅黑';
                        link.fontColor='150,150,150';
                        scene.add(link);
                    }
                });
            }
        }
    }
	//组件加载到容器
    var initContainerJTop = function (se, node) {
		var bundBz = node.bundBz;
		if(bundBz!=null&&bundBz.length>0){
			var arr = toRepeat(bundBz.split(","));
			for(var i = 0; i < arr.length; i++){
				se.childs.forEach(function (c) {
					if (c.elementType == 'container') {
						if (arr[i] == c.id) {
							c.add(node);
							return false;
						}
					}
				});
			}

			//调整布局
			se.childs.forEach(function (a) {
				if (a.elementType == "container") {
					if (a.childs.length == 1) {
						a.layout = JTopo.layout.FlowLayout();
						//a.setLocation(a.childs[0].x, a.childs[0].y);
					} else if (a.childs.length > 1) {
						a.layout = JTopo.layout.AutoBoundLayout();
					}
				}
			});
		}
    }
	//添加事件
	function sceneBundFunction($target,scene){
		
		//获取拓扑图中的设备id,多个id以逗号隔开
		scene.getInstanceIds=function(){
			var insIds=[];
			scene.childs.forEach(function (element) {
				if (element instanceof  JTopo.Node) {
					insIds.push(element.id);
				}
			});
			return insIds.join(",");
		}
		/**
		 * 单棵树递归树布局
		 */
		function recursionTreeLayout(node,treelocation,flag,isFirstRoot) {//flag为时间戳，一次布局必须为同一值
			var outLinks = node.outLinks;
			//isFirstRoot是为了解决除第一棵树外其他树的X轴位置，第一棵树不需要变动位置
			//并且一旦节点setLocationFlag置为flag就再也无法移动
			if(outLinks.length==0){
				return;
			}
			//父节点为中心点
			var centpoint = {x:node.x,y:node.y};
			//已知独有子节点个数，由于左右 
			var count = 0;
			for(var i = 0;i<outLinks.length;i++){
				var toNode = outLinks[i].nodeZ;
				if(toNode.setLocationFlag != flag){
					var step = Math.ceil(count/2);
					if(isFirstRoot){
						toNode.setLocationFlag = flag;
					}
					if(count==0){
						toNode.setLocation(centpoint.x, centpoint.y+150);
					}else if(count%2==0){
						toNode.setLocation(centpoint.x+step*70, centpoint.y+150);
						if(treelocation.right<toNode.x){
							treelocation.right=toNode.x;
						}
					}else{
						toNode.setLocation(centpoint.x-step*70, centpoint.y+150);
						if(treelocation.left>toNode.x){
							treelocation.left=toNode.x;
						}
					}
					count++;
				}
				if(toNode.id!=node.id){
					recursionTreeLayout(toNode,treelocation,flag,isFirstRoot);
				}
			}
			
		}
		//树沿着x轴移动距离
		function treeMoveXLength(node,length,flag) {
			if(node.setLocationFlag!=flag){
				node.setLocation(node.x+length, node.y);
				node.setLocationFlag=flag;
			}
			var outLinks = node.outLinks;
			if(outLinks.length==0){
				return;
			}
			for(var i = 0;i<outLinks.length;i++){
				var toNode = outLinks[i].nodeZ;
				if(node.id!=toNode.id){
					treeMoveXLength(toNode,length,flag);
				}
			}
		}
		/**
		 * 获取跟节点
		 */
		function getRootNodes() {
        	var fromNodes = [];
			var toIds = [];
			var fromIds = ',';
			//所有的fromId和所有的toId
			scene.childs.forEach(function (element) {
				if (element instanceof JTopo.Link) {
					if(fromIds.indexOf(","+element.nodeA.id+",")==-1){
						fromNodes.push(element.nodeA);
						fromIds+=element.nodeA.id+",";
					}
					toIds.push(element.nodeZ.id);
				}
			});
			//过滤出只有from的节点（即跟节点）
			var toIdstr = ","+toIds.join(",")+",";
			for(var i=0;i<fromNodes.length;i++){
				var fNode = fromNodes[i];
				if(toIdstr.indexOf(","+fNode.id+",")>-1){
					fromNodes.splice(i, 1);
					i--;
				}
			}
			return fromNodes;
		}
		/**
         * 圆形布局
         */
        scene.circleLayout = function (){
			/*var layout = {type: 'circle', radius: 100};
			var fromNodes = getFromNodesAndSetLayout(layout);
			
			var centpoint = scene.getCenterLocation();
			for(var i=0;i<fromNodes.length;i++){
				var step = Math.ceil(i/2);
				if(i==0){
					fromNodes[0].setLocation(centpoint.x, centpoint.y);
				}else if(i%2==0){
					fromNodes[i].setLocation(centpoint.x+step*250, centpoint.y);
				}else{
					fromNodes[i].setLocation(centpoint.x-step*250, centpoint.y);
				}
				JTopo.layout.layoutNode(scene, fromNodes[i], true);
			}*/
		}
        /**
         * 树形布局
         */
        scene.treeLayout = function () {
        	var rootNodes = getRootNodes();
			
        	var centpoint = scene.getCenterLocation();
        	var flag = new Date().getTime();
        	//记录拓扑节点的最右端和最左端
        	var topolocation={left:centpoint.x,right:centpoint.x}
        	var treelocation={left:0,right:0};
        	//记录当前树的最左端和最右端
			for(var i=0;i<rootNodes.length;i++){
				var step = Math.ceil(i/2);
				rootNodes[i].setLocation(centpoint.x, 30);
				//初始化零
				var treelocation={left:rootNodes[i].x,right:rootNodes[i].x};
				//单棵树处理
				recursionTreeLayout(rootNodes[i],treelocation,flag,i==0?true:false);
				if(i==0){
					topolocation=treelocation;
				}
				//整棵树移动
				if(i!=0){
					if(i%2==0){
						var length = topolocation.right-treelocation.left+50;
						treeMoveXLength(rootNodes[i],length,flag);
						topolocation.right=treelocation.right+length;
					}else if (i%2!=0) {
						var length = topolocation.left-treelocation.right-50;
						treeMoveXLength(rootNodes[i],length,flag);
						topolocation.left=treelocation.left+length;
					}
				}
			}
		} 
		//显示告警
		scene.showAlarm=function(alarms){
			//var nodeAlarm={node:拓扑节点,alarmLevel:告警级别,alarmNumber:告警数量}
			//清除之前的告警状态
			clearInterval(intervalId);
			for(var i=0;i<nodeAlarms.length;i++){
				nodeAlarms[i].node.alarm=null;
			}
			//获取新的设备告警
			if(alarms!=null&&alarms.length>0){
				for(var i=0;i<alarms.length;i++){
					scene.childs.forEach(function (element) {
						if (element instanceof  JTopo.Node && element.id==alarms[i].instanceId) {
							var nodeAlarm={};
							nodeAlarm.node=element;
							nodeAlarm.alarmLevel=alarms[i].alarmLevel;
							nodeAlarm.alarmNumber=alarms[i].alarmNumber;
							nodeAlarms.push(nodeAlarm);
						}
					});
				}
			}
			//显示告警
			intervalId = setInterval(function(){
				for(var i=0;i<nodeAlarms.length;i++){
					var alarmMsg="";
					var alarmColor="";
					if(nodeAlarms[i].alarmLevel==3){
						alarmMsg="warning告警";
						alarmColor="255,255,0";
					}else if(nodeAlarms[i].alarmLevel==2){
						alarmMsg="error告警";
						alarmColor="255,153,0";
					}else if(nodeAlarms[i].alarmLevel==1){
						alarmMsg="critical告警";
						alarmColor="255,0,0";
					}
					if(nodeAlarms[i].node.alarm == alarmMsg){
						nodeAlarms[i].node.alarm = null;
					}else{
						nodeAlarms[i].node.alarm = alarmMsg;
						nodeAlarms[i].node.alarmColor=alarmColor;
					}
				}
            }, 600);
		}
	}

    //声明插件，调用入口 nodelist:数据源， topoData：初始化数据
    $.fn.topoView = function (topoData) {
        var $target = $(this);
        var height = $(this).height();

        var $toolBar = createToolBar($(this)); //工具栏
        var width = $(this).width();
        $toolBar.width(width - 40);
        createJtopo($toolBar, width-50, height-70); //top图
        canvas = $(this).find("canvas")[0];
        stage = new JTopo.Stage(canvas);
		//stage.eagleEye.visible = true;
        scene = new JTopo.Scene(stage);
        //初始化节点数据
        initTopo(topoData); //加载top图
		sceneBundFunction($target,scene);
		
        return scene;
    }
})();